/**
 * Desenvolvido pela Fábrica de Software do CESUPA.
 * Todos os direitos reservados.
 */
package br.cesupa.fabsoft.nomedoprojeto.system.infra.i18n;

import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * Works with resources bundles (most commonly properties file) in order to
 * introduce internacionalization and localization to the software.
 *
 * @author Breno Leite
 */
public class TranslationService {

    private ResourceBundle resourceBundle;
    private Locale targetLocale;
    private Locale locale;

    public TranslationService(final ResourceBundle resourceBundle,
            final Locale locale) {
        this.setResourceBundle(resourceBundle);
        this.setLocale(locale);
    }

    /**
     * @param wordKey the key used to find the word
     * @return the translated word
     */
    public String translate(final String key) {
        String translatedWord = key;
        if (getResourceBundle() != null &&
                resourceContainsKey(key, getResourceBundle())) {
            translatedWord = getResourceBundle().getString(key);
        }

        return translatedWord;
    }

    /**
     * Checks if the target resource bundle contains a given key.
     * 
     * @param key the key to be searched
     * @param messageBundle the target message bundle
     * @return true if the resource bundle contains the key, false otherwise
     */
    protected boolean resourceContainsKey(final String key,
            final ResourceBundle messageBundle) {
        boolean keyExists = false;

        for (Iterator<String> it = messageBundle.keySet().iterator(); it.hasNext();) {
            String existingKey = it.next();
            if (existingKey.equals(key)) {
                keyExists = true;
            }
        }

        return keyExists;
    }

    /**
     * @return the resourceBundle
     */
    public ResourceBundle getResourceBundle() {
        return resourceBundle;
    }

    /**
     * @param aResourceBundle the resourceBundle to set
     */
    public void setResourceBundle(ResourceBundle resourceBundle) {
        this.resourceBundle = resourceBundle;
    }

    /**
     * @return the locale
     */
    public Locale getLocale() {
        return locale;
    }

    /**
     * @param locale the locale to set
     */
    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    /**
     * @return the targetLocale
     */
    public Locale getTargetLocale() {
        return targetLocale;
    }

    /**
     * @param targetLocale the targetLocale to set
     */
    public void setTargetLocale(Locale targetLocale) {
        this.targetLocale = targetLocale;
    }
}
